package com.fort.teachermanagementsys.controller;

import com.fort.teachermanagementsys.entity.User;
import com.fort.teachermanagementsys.service.UserService;
import com.fort.teachermanagementsys.utils.Result;
import io.swagger.annotations.ApiOperation;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    public UserService userService;


    @ApiOperation("用户注册接口")
    @PostMapping("/register")
    public Result register(@RequestParam(value = "username")String username,
                           @RequestParam(value = "password")String password){
        return userService.register(username,password);
    }


    @PostMapping("/getAllUsers")
    public Result getAllUsers(){
        Result result = new Result();
        result.setMsg("success");
        result.setCode(200);
        result.setDetail(userService.getAllUsers());
        return result;
    }

    @PostMapping("/updatePassword")
    public Result updatePassword(@RequestParam String oldPassword,
                                 @RequestParam String Password,
                                 @RequestParam String rePassword,
                                 Authentication authentication){
        //todo
        return userService.updatePassword(oldPassword,Password,rePassword,authentication);
    }

    // 删除用户
    @PreAuthorize("hasPermission('system:user:delete')")
    @DeleteMapping("/{id}")
    public void deleteUser(@PathVariable Integer id) {
        userService.deleteUser(id);
    }

    // 分配角色
    @PreAuthorize("hasPermission('system:user:assign')")
    @PostMapping("/assignRoles")
    public void assignRoles(@RequestParam Integer userId, @RequestBody List<Integer> roleIds) {
        userService.assignRoles(userId, roleIds);
    }

    // 获取用户关联的角色 ID
    @PreAuthorize("hasPermission('system:user')")
    @GetMapping("/{id}/roleIds")
    public List<Integer> getRoleIdsByUserId(@PathVariable Integer id) {
        return userService.getRoleIdsByUserId(id);
    }

    // 获取单个用户
    @PreAuthorize("hasPermission('system:user')")
    @GetMapping("/{id}")
    public User getUserById(@PathVariable Integer id) {
        return userService.getUserById(id);
    }
}
